let MS = require('./ms')
const setHeader = (config) => {
    let header = {
        'content-type': 'application/json',
        'X-MS-ApplicationId': config.applicationId,
        'X-MS-REST-API-KEY': config.applicationKey,
        'X-MS-APP-ID': config.appid,
        'X-MS-M-APP-ID': config.mAppId
    }
    return header
}

const setHeaderPost = (config) => {
    let header = {
        'content-type': 'application/x-www-form-urlencoded',
        'X-MS-ApplicationId': config.applicationId,
        'X-MS-REST-API-KEY': config.applicationKey,
        'X-MS-APP-ID': config.appid,
        'X-MS-M-APP-ID': config.mAppId
    }
    return header
}

const request = (route, method = 'get', params = {}, data = {}) => {
    return new Promise((resolve, reject) => {
        var header = {}
        if(method == 'GET' || method == 'get') {
            header = setHeader(MS._config)
        } else {
            header = setHeaderPost(MS._config)
        }
        uni.request({
            url:  ((route.indexOf("https://") != -1)||(route.indexOf("http://") != -1)) ? route : MS._config.host + route,
            method: method,
            data: params,
            header: header,
            success: res => {
                if (res.statusCode === 200) {
                    if(res.data.success) {
                        resolve(res.data)
                    } else {
                        reject(res.data.message)
                    }
                } else {
                    reject(res)
                }
            },
            fail: err => {
                console.log(err)
                reject(err)
            }
        })
    })
}

module.exports = request